﻿using System;
using System.Collections.Generic;
using System.Linq;
using Medianamik.Client.Data;
using Medianamik.Core;
using Medianamik.Core.DAL;
using Medianamik.Core.DAL.Repositories;
using Medianamik.UI.Web.MVP.Presentation;
using Medianamik.UI.Web.TypeList.Data;

namespace Medianamik.UI.Web.TypeList.Presentation.Presenters
{
    public abstract class TypeListPresenter<T, TView> : ModulePresenterWithGrid<T, TView, IMedianamikRepository<T>,
            INodeTypeRepository, IMedianamikRepository<IMedianamikDTOWithName>>
        where T : class, IBaseType
        where TView : class, ITypeList
    {
        protected TypeListPresenter(TView view, IMedianamikRepository<T> repository, INodeTypeRepository nodeTypeRepository,
            IMedianamikRepository<IMedianamikDTOWithName> baseTypeRepository)
            : base(view, repository, nodeTypeRepository, baseTypeRepository)
        {
        }

        protected override void Initialize(object sender, EventArgs e)
        {
            View.NodeTypeChanged += NodeTypeChanged;
            if (!View.IsPostBack)
            {
                View.NodeTypes = NodeTypes;
            }
            base.Initialize(sender, e);
        }

        protected virtual void NodeTypeChanged(object sender, MVP.IdEventArgs e)
        {
            View.AddButton.NavigateUrl = AddUrl;
            Bind();
        }

        private IList<NodeType> _nodeTypes;

        protected virtual IList<NodeType> NodeTypes
        {
            get { return _nodeTypes ?? (_nodeTypes = Utilities.GetListableTypes()); }
        }

        protected override Guid? ParentNodeId
        {
            get
            {
                return null;
            }
        }

        protected override PagedCollection<T> GetData()
        {
            return View.BaseTypeId == Guid.Empty ? 
                new PagedCollection<T>(Enumerable.Empty<T>(), 0) : base.GetData();
        }

        protected override Guid ModuleNodeId
        {
            get { return Modules.TypeList; }
        }
    }

    public class TypeListPresenter : TypeListPresenter<BaseType, ITypeList>
    {
        public TypeListPresenter(NodeTypeList view, IMedianamikRepository<BaseType> repository, 
            INodeTypeRepository nodeTypeRepository, IMedianamikRepository<IMedianamikDTOWithName> baseTypeRepository) : 
            base(view, repository, nodeTypeRepository, baseTypeRepository)
        {
        }
    }
}
